package com.thyrsus.project.controller.user;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.thyrsus.project.form.user.UserForm;
import com.thyrsus.project.helper.Constants;
import com.thyrsus.project.helper.LocaleHelper;
import com.thyrsus.project.helper.SessionHelper;
import com.thyrsus.project.helper.URLHelper;
import com.thyrsus.project.helper.UserHelper;
import com.thyrsus.project.object.UserContext;
import com.thyrsus.project.service.user.UserService;

import org.apache.log4j.Logger;

@Controller
@SessionAttributes
public class NewUserController {

	static Logger LOGGER = Logger.getLogger(ConnexionUserController.class);
	
	@Autowired
	UserService userService;
	
	@RequestMapping(value = "/admin/create")
    public String doCreateAdmin(HttpServletRequest request,HttpServletResponse response) {
		
		userService.createAdmin();
		
		return "redirect:/home";
	}
	
	@RequestMapping(value = "/user/register", method = RequestMethod.POST)
    public ModelAndView doRegister(@ModelAttribute("userForm")
                            UserForm userForm, BindingResult result, HttpServletRequest request,HttpServletResponse response) {
		boolean mailExist = userService.isMailExist(userForm.getMail());
		if (!mailExist && UserHelper.validateUserForm(userForm)) {
			UserContext userContext = new UserContext(userForm);
			LOGGER.debug(userContext.getMail()+" is registering with the password : "+userContext.getPassword());
			userContext.setLocale(LocaleHelper.getLocale(request));
			userService.create(userContext);
			
			if (userContext!=null) {
				SessionHelper.setAttribute(request,Constants.USER_CONTEXT, userContext);
				SessionHelper.removeAttribute(request,Constants.ERROR_LOGIN);
			}
		} else if (mailExist) {
			SessionHelper.setAttribute(request,Constants.ERROR_LOGIN, "error-mail");
		} else {
			SessionHelper.setAttribute(request,Constants.ERROR_LOGIN, "error");
		}
		return new ModelAndView(URLHelper.getURL("/user/login-ajax_result",request));
	}
}
